 #include "halokpy.h"
#include "./ui_halokpy.h"

#include <QDebug>
#include <QSqlQueryModel>
#include <QTimer>
#include <QAbstractItemView>
#include <QHeaderView>
#include <QTableView>
#include <QTreeView>
#include <QSplitter>
#include <QChartView>
#include <QPieSeries>
#include <QPieSlice>
#include <QLegendMarker>
#include <QToolTip>

#include <QGraphicsWidget>
#include <QFontMetrics>
#include <QPainter>
#include <QGraphicsLinearLayout>
#include <QMessageBox>
#include <QFileInfo>
#include <QFileDialog>
#include <QProcess>

#include "qpagebar.h"
#include "publicstruct.h"

#include "xlsxdocument.h"
//#include "xlsxchartsheet.h"
//#include "xlsxcellrange.h"
//#include "xlsxchart.h"
//#include "xlsxrichstring.h"
#include "xlsxworkbook.h"
//#include "loger.h"

using namespace QXlsx;

struct Element {
    float value;
    QString groupName;
};

class MyDateTimeScaleFormatter1 : public KDGantt::DateTimeScaleFormatter
{
public:
    MyDateTimeScaleFormatter1() : DateTimeScaleFormatter(Month, "MM"){}

//    /*reimp*/QDateTime nextRangeBegin(const QDateTime& datetime) const
//    {
//        return currentRangeBegin(datetime).addMonths(1);
//    }
//    /*reimp*/QDateTime currentRangeBegin(const QDateTime& datetime) const
//    {
//        return datetime;
//    }

    /*reimp*/QString text(const QDateTime& dt) const
    {
        return QObject::tr("%1年%2月").arg(dt.date().year()).arg(dt.date().month());
    }
};
class MyStandardItem : public QStandardItem
{
public:
    MyStandardItem(const QVariant &v)
        : QStandardItem()
    {
        setData(v, Qt::DisplayRole);
        // setFlags( flags() & ~Qt::ItemIsEditable );
    }
    MyStandardItem(const QString &v)
        : QStandardItem()
    {
        setData(v, Qt::DisplayRole);
        // setFlags( flags() & ~Qt::ItemIsEditable );
    }
    MyStandardItem(const QDate &dt, int role,int rolo1)
        : QStandardItem()
    {
        setData(QVariant::fromValue(dt), role);
        setData(QVariant::fromValue(dt), rolo1);
    }
};

class CustomLegendItem : public QGraphicsWidget
{
public:
    CustomLegendItem(const QString& label, const QColor& color, QGraphicsItem* parent = nullptr)
        : QGraphicsWidget(parent), m_label(label), m_color(color)
    {
        setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
        setMinimumHeight(20);
    }

    QSizeF sizeHint(Qt::SizeHint hint, const QSizeF& size = QSizeF()) const override
    {
        if (hint == Qt::PreferredSize)
        {
            QFontMetrics fm(font());
            QSizeF textSize = fm.size(Qt::TextSingleLine, m_label);
            return QSizeF(textSize.width() + 30, 20);
        }
        return QGraphicsWidget::sizeHint(hint, size);
    }

protected:
    void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override
    {
        Q_UNUSED(option);
        Q_UNUSED(widget);

        QRectF rect = boundingRect();
        painter->setRenderHint(QPainter::Antialiasing);
        painter->setPen(Qt::NoPen);
        painter->setBrush(m_color);
        painter->drawRect(rect.topLeft().x()+15,rect.topLeft().y()+5,15,15);

        painter->setPen(Qt::black);
        painter->setFont(font());
        painter->drawText(rect.adjusted(45, 0, 0, 0), Qt::AlignVCenter, m_label);
    }

private:
    QString m_label;
    QColor m_color;
};

HaloKpy::HaloKpy(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::HaloKpy)
{
    ui->setupUi(this);
    this->setWindowTitle("靠谱云项目管理");
    m_versionNum = "1.0.1";
    m_exeFileName = "HaloKpy.exe";
    m_strRemoteUrl ="http://10.35.19.63:8091/autoupdate/autoupdate.json";
 //   this->resize( QSize( 800, 600 ));
    this->dbSqlite = new database();
    this->dbSqlite->initSqlite();
    this->dbSqlite->initCfgData();

    this->dbMySql = new database();
    this->dbMySql->mySqlInfo =this->dbSqlite->mySqlInfo;
    this->dbMySql->initMysql();

    m_taskByProject = new TaskByProject(this);

    //initProjectTaskGnt();
//    initDeveloperTaskGnt();
//    initDeptDevHours();
//    initProjectVerPlan();
    ui->stackedWidget->addWidget(m_taskByProject);
    ui->stackedWidget->setCurrentWidget(m_taskByProject);
    //ui->stackedWidget->setCurrentWidget(ui->ver sionPlanGnt);
}

HaloKpy::~HaloKpy()
{
    delete ui;
}


void HaloKpy::initDeveloperTaskGnt()
{
    initComboBoxData(ui->comboBox12,"研发人员","");
    QDate curdate = QDate::currentDate();

    ui->dateEdit_3->setMaximumDate(curdate);
    ui->dateEdit_3->setMinimumDate(curdate.addDays(-30));
    ui->dateEdit_4->setMinimumDate(curdate);
    ui->dateEdit_4->setMaximumDate(curdate.addDays(30));

    QDate sDate=ui->dateEdit_3->date();
    QDate eDate =ui->dateEdit_4->date();
    m_developerTaskGnt = new GanttModel() ;

    //设置列表view的表头
    QStringList headlist;
    headlist <<"任务名称"<<"类型"<<"开始日期"<<"结束日期"<<"项目名称"<<"累计耗时";
    m_developerTaskGnt->SetHorHeaderData(headlist);

    QVector<int> headListWidth = {300,40,80,80,120,60,}; // 设置列宽
    m_developerTaskGnt->SetHeaderWidth(headListWidth);

    m_developerTaskGnt->SetStartEndData(sDate,eDate);
    QVBoxLayout *m_vlayout1 = new QVBoxLayout();
    m_vlayout1->addWidget(m_developerTaskGnt);
    ui->widget_321->setLayout(m_vlayout1);
    connect(m_developerTaskGnt->m_pageBar, &QPageBar::pageChanged, this, [&](int idx) {reflashPagingModelView_new(m_developerTaskGnt,idx);});

}

void HaloKpy::initProjectTaskGnt()
{
    qDebug()<<"initProjectTaskGnt";
    initComboBoxData(ui->comboBox_23,"项目名称","");
    QDate curdate = QDate::currentDate();

    ui->dateEdit->setMaximumDate(curdate);
    ui->dateEdit->setMinimumDate(curdate.addDays(-30));
    ui->dateEdit_2->setMinimumDate(curdate);
    ui->dateEdit_2->setMaximumDate(curdate.addDays(30));

    QDate sDate=ui->dateEdit->date();
    QDate eDate =ui->dateEdit_2->date();
    m_projectTaskGnt = new GanttModel() ;

    //设置列表view的表头
    QStringList headlist;
    headlist <<"任务名称"<<"类型"<<"开始日期"<<"结束日期"<<"研发人员"<<"累计耗时";
    m_projectTaskGnt->SetHorHeaderData(headlist);

    QVector<int> headListWidth = {420,40,80,80,60,60,}; // 设置列宽
    m_projectTaskGnt->SetHeaderWidth(headListWidth);

    m_projectTaskGnt->SetStartEndData(sDate,eDate);
    QVBoxLayout *m_vlayout = new QVBoxLayout();
    m_vlayout->addWidget(ui->widget_prjplan,1);
    m_vlayout->addWidget(m_projectTaskGnt,19);
    ui->projectTaskGnt->setLayout(m_vlayout);
    connect(m_projectTaskGnt->m_pageBar, &QPageBar::pageChanged, this, [&](int idx) {reflashPagingModelView_new(m_projectTaskGnt,idx);});
}

void HaloKpy::initProjectVerPlan()
{
    initComboBoxData(ui->combProductName,"产品名称","");
    initComboBoxData(ui->combVerPlan,"迭代版本号",ui->combProductName->currentText());

    ui->dateEdit_5->setReadOnly(true);
    ui->dateEdit_6->setReadOnly(true);

    mlayout  = new QVBoxLayout();
    mlayout->addWidget(&view);

    view.splitter()->setStretchFactor(0, 1);
    view.splitter()->setStretchFactor(1, 3);

    //设置甘特图的表头

    KDGantt::DateTimeScaleFormatter *upperFormatter,*lowerFormatter;

    grid.setUserDefinedUpperScale(new MyDateTimeScaleFormatter1());

    lowerFormatter = new KDGantt::DateTimeScaleFormatter(KDGantt::DateTimeScaleFormatter::Day,
                                                         QString::fromLatin1("dd"),
                                                         QString::fromLatin1("%1"),
                                                         Qt::AlignHCenter);
    grid.setUserDefinedLowerScale(lowerFormatter);
    grid.setScale(KDGantt::DateTimeGrid::ScaleUserDefined);
    grid.setDayWidth(38.);//设置甘特图的每天的宽度

    //grid.setStartDateTime(QDateTime::currentDateTime().addDays(-30));
    // grid.setNoInformationBrush( Qt::NoBrush );
    view.setGrid(&grid);
    view.setModel(&model);

    QStringList headlist;
    headlist <<"需求任务名称"<<"类型"<<"开始日期"<<"结束日期"<<"状态"<<"研发人员"<<"累计耗时";
    model.setHorizontalHeaderLabels(headlist);



    ui->wgPrjVerPlan->setLayout(this->mlayout);
    auto *leftView = qobject_cast<QTreeView *>(view.leftView());
    Q_ASSERT(leftView);
    leftView->header()->setStyleSheet("QHeaderView::section {background-color:#1E90FF;}");
    leftView->setColumnHidden(1, true);

    leftView->header()->setStretchLastSection(true);
    leftView->setColumnWidth(0,600);
    leftView->setColumnWidth(2,90);
    leftView->setColumnWidth(3,90);
    leftView->setColumnWidth(4,60);
    leftView->setColumnWidth(5,60);
    leftView->setColumnWidth(6,60);

 //   leftView->setAlternatingRowColors(true);
    leftView->setStyleSheet("QTreeView::item{height:30px;alternate-background-color:rgb(135,206,235);}");

    connect(view.leftView(), SIGNAL(doubleClicked(const QModelIndex &)), this,SLOT(slotRowDoubleClicked(const QModelIndex &)));
}

void HaloKpy::on_combProductName_currentTextChanged(const QString &arg1)
{
    initComboBoxData(ui->combVerPlan,"迭代版本号",arg1);
}

void HaloKpy::initComboBoxData(QComboBox *cbox, const QString &dataType,const QString &dataCondition)
{
    qDebug()<<"initComboBoxData:"<<dataType<<dataCondition;
    QString sqlStr;
    cbox->clear();
    if(dataType=="项目名称"){

        sqlStr="select zp.name  from zt_project zp where zp.status ='doing' and zp.deleted =1 order by zp.name";
        cbox->addItems(dbMySql->getComboBoxDataBySql(sqlStr));

    }else if(dataType=="迭代版本号"){

        m_prjVerPlan.clear();
        m_prjVerPlan = dbMySql->getProjectVerPlan(dataCondition);
        QStringList sList;
        for(int i=0;i<m_prjVerPlan.size();i++)
        {
            sList<<m_prjVerPlan[i].verPlanName;
        }
        cbox->addItems(sList);

    }else if(dataType=="研发人员"){
        sqlStr="select realname from zt_user where deleted =1 and role not in ('cpo','om') and dept in (83,82,104,79,77,78,81,85,86,87,90,91,92,94,93) order by realname ";
        cbox->addItems(dbMySql->getComboBoxDataBySql(sqlStr));

    }else if(dataType=="产品名称"){
        sqlStr="select zp.name from zt_product zp where zp.deleted =1 and zp.status = 'normal' order by zp.name";
        cbox->addItems(dbMySql->getComboBoxDataBySql(sqlStr));

    }else {
        qDebug()<< "initComboBoxData is invalid:"<< dataType;
    }
}

void HaloKpy::reflashPagingModelView_new(GanttModel *prjGntModel, int curPage)
{
    prjGntModel->m_pageBar->m_currentPage = curPage;
    int modelType = prjGntModel->GetDataModelType();
    QList<GanttTask> gntTask;
    if(modelType==1)//根据项目名称获取项目任务
            gntTask=dbMySql->getTaskDataByPrjName_new(prjGntModel->m_pageBar);
    if(modelType==2)//根据开发人员姓名获取人员任务
            gntTask=dbMySql->getTaskDataByDevName_new(prjGntModel->m_pageBar);
    else
            qDebug()<<"unknown datamodeltype:"<<modelType;
    prjGntModel->BindModelData(gntTask);
    prjGntModel->SetGanttModel();
}


void HaloKpy::initPersonPie(QList<PersonHours> &hoursList)
{
    QMap<QString, float> sumByGroup;
    float totalHours=0.0,hour=0.0;

    foreach (PersonHours element, hoursList)
    {
            // 根据组名获取当前组的和，若不存在则初始化为0
            if (!sumByGroup.count(element.projectName))
            {
                sumByGroup[element.projectName] = 0;
            }
            // 更新当前组的和
            hour = element.consumed.toFloat();
            sumByGroup[element.projectName] += hour;
            totalHours+=hour;
 //           qDebug() <<"hour:"<<hour<<"totalHours:"<<totalHours;
    }
    // 输出每个组的和

    for (auto itr = sumByGroup.begin(); itr != sumByGroup.end(); ++itr) {
            qDebug() << itr.key() << ": " << itr.value()<<totalHours;
    }
    //删除原来的布局,设置新的布局
    if(ui->widget_342->layout()!=NULL)
            delete ui->widget_342->layout();

    QVBoxLayout *main_layout = new QVBoxLayout();


    QChartView* view = new QChartView();
    main_layout->addWidget(view);
    ui->widget_342->setLayout(main_layout);
    QChart* chart = new QChart();
    chart->setTitle("项目工时统计【"+QString::number(totalHours)+"】");
    chart->legend()->setAlignment(Qt::AlignBottom);//AlignLeft);
    view->setChart(chart);

    QPieSeries* series = new QPieSeries();
    series->setName("项目工时：饼状图");

    chart->addSeries(series);

    QPieSlice* slice;
    QList<QColor> colorList;
    QList<QString> lenendString1,lenendString2;

    colorList.append(QColor(255,99,71));
    colorList.append(QColor(50,205,50));
    colorList.append(QColor(237,145,33));
    colorList.append(QColor(135,206,235));
    colorList.append(QColor(218,112,214));
    int i=0;
    for (auto itr1 = sumByGroup.begin(); itr1 != sumByGroup.end(); ++itr1) {
         //   qDebug() << itr1.key() << ": " << itr1.value();
            slice = new QPieSlice();
            //slice->setLabel(QString::number(itr1.value()));
            QString a = QString::number(itr1.value()/totalHours*100,'f',0);
            slice->setLabel(a+"%");
            slice->setLabelPosition(QPieSlice::LabelInsideHorizontal);
            slice->setLabelVisible(true);
            slice->setValue(itr1.value()/totalHours);
            slice->setColor(colorList.at(i));
            lenendString1.append(itr1.key());
            lenendString2.append(QString::number(itr1.value()));
           // chart->legend()->markers().at(i)->setLabel(itr1.key());
            i++;

            series->append(slice);
    }

    //qDebug()<<"series:"<<series->count();
    int j=0;
//    foreach (QLegendMarker* marker, chart->legend()->markers())
//    {
//            marker->setLabel(lenendString1.at(j)+":"+lenendString2.at(j)+"\n总工时:"+QString::number(totalHours));
//            j++;
//    }
    j=0;
    QGraphicsLinearLayout* layout = new QGraphicsLinearLayout(Qt::Vertical);
    // 添加自定义图例项
    for (QPieSlice* slice1 : series->slices())
    {
            QString label = lenendString1.at(j)+":"+lenendString2.at(j);
            QColor color = slice1->color();
            qDebug()<<label<<color;
            CustomLegendItem* item = new CustomLegendItem(label, color);
            layout->addItem(item);
            j++;
    }
    chart->legend()->setLayout(layout);
    //series->setVerticalPosition(0.15);
}

void HaloKpy::on_actionProjectTaskGnt_triggered()
{
    //ui->stackedWidget->setCurrentWidget(ui->projectTaskGnt);
    qDebug()<<"on_actionProjectTaskGnt_triggered";
    ui->stackedWidget->setCurrentWidget(m_taskByProject);
}

void HaloKpy::on_actionPersonTaskGnt_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->developerTaskGnt);
}

void HaloKpy::on_btn_devtaskgnt_qry_clicked()
{
    QString userName = ui->comboBox12->currentText();

    // 获取记录总数
    QDate showStartDate = ui->dateEdit_3->date();
    QDate showEndDate = ui->dateEdit_4->date();
    QString startDate = showStartDate.toString("yyyy-MM-dd");
    QString endDate = showEndDate.toString("yyyy-MM-dd");

    m_developerTaskGnt->m_pageBar->m_strWhere = QString(" from zt_task zt  left join zt_project zp on zp.id = zt.project  left join zt_user zu on (zu.account = zt.assignedTo or zu.account = zt.finishedBy ) left join zt_story zs on zs.id = zt.story  left join custom_role cr on cr.`key` = zu.`role` where zu.realname ='%1' and zp.status = 'doing' and zt.deleted =1 and ((zt.estStarted <= '%2' and zt.deadline >='%3') or (zt.estStarted <='%4' and zt.deadline >='%5') or (zt.estStarted >= '%6' and zt.deadline <='%7'))")
                                              .arg(userName)
                                              .arg(startDate)
                                              .arg(startDate)
                                              .arg(endDate)
                                              .arg(endDate)
                                              .arg(startDate)
                                              .arg(endDate);
    m_developerTaskGnt->m_pageBar->m_strCols = " zp.name,zs.title,zt.id,zt.name,zt.status,zu.realname,cr.value,zt.estStarted,zt.deadline,zt.consumed ";
    dbMySql->getPagingInfo(
        m_developerTaskGnt->m_pageBar /*,m_pageBar->m_strWhere*/
        /*,m_pageBar->m_pageRecCount*/);

    m_developerTaskGnt->m_pageBar->m_strOrd = QString(" order by zp.name asc ");
    m_developerTaskGnt->SetStartEndData(showStartDate,showEndDate);
    m_developerTaskGnt->SetDataModelType(2);
    reflashPagingModelView_new(m_developerTaskGnt,1);

    QList<PersonHours> hoursList;
    hoursList=dbMySql->getPersonHours(userName, showStartDate, showEndDate);
    initPersonPie(hoursList);
}

void HaloKpy::on_btnPrjTaskQuery_clicked()
{
    QString projectName = ui->comboBox_23->currentText();

    QDate showStartDate = ui->dateEdit->date();
    QDate showEndDate = ui->dateEdit_2->date();
    QString startDate = showStartDate.toString("yyyy-MM-dd");
    QString endDate = showEndDate.toString("yyyy-MM-dd");

    m_projectTaskGnt->m_pageBar->m_strWhere = QString(" from zt_task zt  left join zt_project zp on zp.id = zt.project  left join zt_user zu on (zu.account = zt.assignedTo or zu.account = zt.finishedBy ) left join zt_story zs on zs.id = zt.story  left join custom_role cr on cr.`key` = zu.`role` where zp.name ='%1' and zp.status = 'doing' and zt.deleted =1 and ((zt.estStarted <= '%2' and zt.deadline >='%3') or (zt.estStarted <='%4' and zt.deadline >='%5') or (zt.estStarted >= '%6' and zt.deadline <='%7'))")
                                                  .arg(projectName)
                                                  .arg(startDate)
                                                  .arg(startDate)
                                                  .arg(endDate)
                                                  .arg(endDate)
                                                  .arg(startDate)
                                                  .arg(endDate);
    m_projectTaskGnt->m_pageBar->m_strCols = " zp.name,zs.title,zt.id,zt.name,zt.status,zu.realname,cr.value,zt.estStarted,zt.deadline,zt.consumed ";
    dbMySql->getPagingInfo(m_projectTaskGnt->m_pageBar/*,m_pageBar->m_strWhere*//*,m_pageBar->m_pageRecCount*/);

    m_projectTaskGnt->m_pageBar->m_strOrd = QString(" order by zp.name,zu.realname  asc ");//limit %1,%2").arg(m_pageBar->m_pageRecCount*m_pageBar->m_currentPage).arg(m_pageBar->m_pageRecCount);

    m_projectTaskGnt->SetStartEndData(showStartDate,showEndDate);
    m_projectTaskGnt->SetDataModelType(1);
    reflashPagingModelView_new(m_projectTaskGnt,1);
}


void HaloKpy::on_actionDeptDevHours_triggered()
{


    ui->stackedWidget->setCurrentWidget(ui->deptDevHours);
}

void HaloKpy::initDeptDevHours()
{
    QDate curdate = QDate::currentDate();

    ui->dateStart->setMaximumDate(curdate);
    ui->dateStart->setMinimumDate(curdate.addDays(-60));
    ui->dateEnd->setMinimumDate(curdate.addDays(-60));
    ui->dateEnd->setMaximumDate(curdate.addDays(60));

    ui->combQuickDate->addItem("上周");
    ui->combQuickDate->addItem("本周");
    ui->combQuickDate->addItem("本月");
    ui->combQuickDate->addItem("上月");

    ui->horizontalLayout->setSpacing(15);//设置控件之间的间隔

    m_totalHoursModel = new QStandardItemModel();
    ui->tabTotalHours->setModel(m_totalHoursModel);
    QStringList tabHeadersTotalName;
    tabHeadersTotalName << "团队名称" << "姓名" << "工时数";
    m_totalHoursModel->setHorizontalHeaderLabels(tabHeadersTotalName);
    ui->tabTotalHours->horizontalHeader()->setFixedHeight(35);
    ui->tabTotalHours->verticalHeader()->setDefaultSectionSize(25);//设置列的行高
    ui->tabTotalHours->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:#1E90FF;}");
    ui->tabTotalHours->setAlternatingRowColors( true );//交替颜色背景
    ui->tabTotalHours->setStyleSheet("alternate-background-color:rgb(135,206,235);");
    ui->tabTotalHours->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tabTotalHours->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tabTotalHours->setColumnWidth(1, 100);//设置列宽
    ui->tabTotalHours->setColumnWidth(2, 70);
    ui->tabTotalHours->setColumnWidth(3, 60);
//-------------------------------------------------------------------------------------------------------------
    m_detailHoursModel = new QStandardItemModel();
    ui->tabDetailHours->setModel(m_detailHoursModel);
    QStringList tabHeadersDetailName;
    tabHeadersDetailName << "项目名称" << "任务名称" << "任务状态"<<"填写日期" << "填写工时"<< "任务描述";
    m_detailHoursModel->setHorizontalHeaderLabels(tabHeadersDetailName);
    ui->tabDetailHours->horizontalHeader()->setFixedHeight(35);
    ui->tabDetailHours->verticalHeader()->setDefaultSectionSize(25);
    ui->tabDetailHours->horizontalHeader()->setStyleSheet("QHeaderView::section {background-color:#1E90FF;}");
    ui->tabDetailHours->setAlternatingRowColors( true );
    ui->tabDetailHours->setStyleSheet("alternate-background-color:rgb(135,206,235);");
    ui->tabDetailHours->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tabDetailHours->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tabDetailHours->setColumnWidth(0, 160);
    ui->tabDetailHours->setColumnWidth(1, 650);
    ui->tabDetailHours->setColumnWidth(2, 60);
    ui->tabDetailHours->setColumnWidth(3, 80);
    ui->tabDetailHours->setColumnWidth(4, 60);
    ui->tabDetailHours->setColumnWidth(5, 520);
    ui->tabDetailHours->setMouseTracking(true);
    connect(ui->tabDetailHours,SIGNAL(entered(QModelIndex)),this,SLOT(ShowTooltip(QModelIndex)));

}


void HaloKpy::on_combQuickDate_currentTextChanged(const QString &arg1)
{
    QDate date = QDate::currentDate();
    if(arg1 == "本周")
    {
            date = date.addDays(-date.dayOfWeek()+1);
            ui->dateStart->setDate(date);
            ui->dateEnd->setDate(date.addDays(6));
    }
    else if(arg1 =="上周")
    {
            date = date.addDays(-date.dayOfWeek()+1);
            ui->dateStart->setDate(date.addDays(-7));
            ui->dateEnd->setDate(date.addDays(-1));
    }
    else if(arg1 =="本月")
    {
            ui->dateStart->setDate(QDate(date.year(),date.month(),1));
            ui->dateEnd->setDate(QDate(date.year(),date.month(),date.daysInMonth()));
    }
    else if(arg1 == "上月")
    {
            date = date.addMonths(-1);
            ui->dateStart->setDate(QDate(date.year(),date.month(),1));
            ui->dateEnd->setDate(QDate(date.year(),date.month(),date.daysInMonth()));
    }
}


void HaloKpy::on_btnQueryHours_clicked()
{
    QString sDate = ui->dateStart->date().toString("yyyy-MM-dd");
    QString eDate = ui->dateEnd->date().toString("yyyy-MM-dd");
    QList<DeptDevTotalHours> hoursList = dbMySql->getDeptDevTotalHours(sDate,eDate);
    int idx=0;
    for (const auto& value : hoursList) {
    //  qDebug() << value;
        m_totalHoursModel->setItem(idx, 0, new QStandardItem(value.teamName));
        m_totalHoursModel->setItem(idx, 1, new QStandardItem(value.userName));
        m_totalHoursModel->setItem(idx, 2, new QStandardItem(value.consumed));
        idx++;
    }

}


void HaloKpy::on_tabTotalHours_doubleClicked(const QModelIndex &index)
{
    int idx =  ui->tabTotalHours->selectionModel()->currentIndex().row();
    QStandardItem *item = m_totalHoursModel->item(idx,1);
    QString userName = item->text();

    QString sDate = ui->dateStart->date().toString("yyyy-MM-dd");
    QString eDate = ui->dateEnd->date().toString("yyyy-MM-dd");
    QList<DevDetailHours> detailList = dbMySql->getDevDetailHours(userName,sDate,eDate);

    m_detailHoursModel->removeRows(0,m_detailHoursModel->rowCount());
    idx=0;
    for (const auto& value : detailList) {
        //  qDebug() << value;
        m_detailHoursModel->setItem(idx, 0, new QStandardItem(value.projectName));
        m_detailHoursModel->setItem(idx, 1, new QStandardItem(value.taskName));
        m_detailHoursModel->setItem(idx, 2, new QStandardItem(value.taskStatus));
        m_detailHoursModel->setItem(idx, 3, new QStandardItem(value.writeDate));
        m_detailHoursModel->setItem(idx, 4, new QStandardItem(value.consumed));
        m_detailHoursModel->setItem(idx, 5, new QStandardItem(value.taskDesc));
        idx++;
    }

}

void HaloKpy::ShowTooltip(QModelIndex index)
{
    QToolTip::showText(QCursor::pos(),index.data().toString());
    return ;
}

void HaloKpy::on_actionVerPlan_triggered()
{
    ui->stackedWidget->setCurrentWidget(ui->versionPlanGnt);
}

void HaloKpy::on_btnQureyVerPlan_clicked()
{
    QString verPlanName = ui->combVerPlan->currentText();
    QString verPlanId,sVerDate,eVerDate;
    for(int i=0;i<m_prjVerPlan.size();i++)
    {
        if(m_prjVerPlan[i].verPlanName ==verPlanName)
        {
            verPlanId = m_prjVerPlan[i].verPlanId;
            sVerDate = m_prjVerPlan[i].verStartDate;
            eVerDate = m_prjVerPlan[i].verEndDate;
            break;
        }
    }

    QList<StoryTaskByVer> recList = dbMySql->getStoryTaskByVerPlan(verPlanId);

    model.removeRows(0, model.rowCount());
    QBrush brush(QColor(135,206,235));

    int verNum = recList.size();
    QStandardItem *storyItem;
    qDebug() << "start:" << QDateTime::currentDateTime() << verPlanId << verNum;
    for (int i = 0; i < verNum; i++) {
        if (i == 0) {
                storyItem = new MyStandardItem(recList.at(i).storyName);
                storyItem->setData(brush, Qt::BackgroundRole);
                if (recList.at(i).taskName.length()) {
                    storyItem->appendRow(QList<QStandardItem *>()
                                         << new MyStandardItem(recList.at(i).taskName)
                                         << new MyStandardItem(KDGantt::TypeTask)
                                         << new MyStandardItem(recList.at(i).taskStartDate,Qt::DisplayRole,KDGantt::StartTimeRole)
                                         << new MyStandardItem(recList.at(i).taskEndDate,Qt::DisplayRole,KDGantt::EndTimeRole)
                                         << new MyStandardItem(recList.at(i).taskStatus)
                                         << new MyStandardItem(recList.at(i).taskUser)
                                         << new MyStandardItem(recList.at(i).taskConsumed));
                }
                model.appendRow(QList<QStandardItem *>()
                                << storyItem << new MyStandardItem(KDGantt::TypeMulti /*Summary*/)
                                << new MyStandardItem(QString()) << new MyStandardItem(QString())
                                << new MyStandardItem(QString()));
        } else {
                if (recList.at(i).storyName != recList.at(i - 1).storyName) {
                    storyItem = new MyStandardItem(recList.at(i).storyName);
                    storyItem->setData(brush, Qt::BackgroundRole);
                }
                if (recList.at(i).taskName.length()) {
                    storyItem->appendRow(QList<QStandardItem *>()
                                         << new MyStandardItem(recList.at(i).taskName)
                                         << new MyStandardItem(KDGantt::TypeTask)
                                         << new MyStandardItem(recList.at(i).taskStartDate,Qt::DisplayRole,KDGantt::StartTimeRole)
                                         << new MyStandardItem(recList.at(i).taskEndDate,Qt::DisplayRole,KDGantt::EndTimeRole)
                                         << new MyStandardItem(recList.at(i).taskStatus)
                                         << new MyStandardItem(recList.at(i).taskUser)
                                         << new MyStandardItem(recList.at(i).taskConsumed));
                }
                if (recList.at(i).storyName != recList.at(i - 1).storyName) {
                    model.appendRow(
                        QList<QStandardItem *>()
                        << storyItem << new MyStandardItem(KDGantt::TypeMulti /*Summary*/)
                        << new MyStandardItem(QString()) << new MyStandardItem(QString())
                        << new MyStandardItem(QString()));
                }
        }
    }
    auto *leftView = qobject_cast<QTreeView *>(view.leftView());
    leftView->expandAll();
    grid.setStartDateTime(QDateTime::fromString(sVerDate, "yyyy-MM-dd"));
    qDebug() << "end:" << QDateTime::currentDateTime();
}

void HaloKpy::slotRowDoubleClicked(const QModelIndex index)
{
    QAbstractItemModel *model = view.model();
    QModelIndex indexCurr = model->index(index.row(), 0);
    QString verString = model->data(indexCurr).toString();
    QMessageBox::StandardButton result = QMessageBox::information(this, "Title",verString);

}

void HaloKpy::on_combVerPlan_currentTextChanged(const QString &arg1)
{
    for(int i=0;i<m_prjVerPlan.size();i++)
    {
        if(m_prjVerPlan[i].verPlanName ==arg1)
        {
                ui->dateEdit_5->setDate(QDate::fromString(m_prjVerPlan[i].verStartDate,"yyyy-MM-dd"));
                ui->dateEdit_6->setDate(QDate::fromString(m_prjVerPlan[i].verEndDate,"yyyy-MM-dd"));
                break;
        }
    }
}


void HaloKpy::on_btnExportHours_clicked()
{

    //xlsx导出
    QXlsx::Document xlsx;
    QStringList titleList;
    QString filePathName;
    QString defaultFileName = "工时汇总.xls";

    // 设置保存的默认文件名称
    QFileInfo fileinfo(defaultFileName);
    // 获取保存文件路径
    QFileDialog *fileDlg = new QFileDialog(this);
    fileDlg->setWindowTitle("保存文件");
    fileDlg->setAcceptMode(QFileDialog::AcceptSave);
    fileDlg->selectFile(defaultFileName);
    fileDlg->setNameFilter("Excel Files(*.xls *.xlsx)");
    fileDlg->setDefaultSuffix("xls");

    if (fileDlg->exec() != QDialog::Accepted)//点击保存
        return;

    filePathName = fileDlg->selectedFiles().at(0);

    // 保存文件添加后缀名
    fileinfo =  QFileInfo(filePathName);
    if (fileinfo.suffix() != "xls" && fileinfo.suffix() != "xlsx")
    {
        filePathName += ".xls";
    }

    // 设置excel表头（第一行数据）
    titleList <<"团队名称"<<"姓名"<<"工时数";

    for (int i = 0; i < titleList.size(); i++)
    {
        xlsx.write(1, i+1, titleList.at(i));//
        xlsx.setColumnWidth(i, 30);//第一行,20列宽
    }

    //开始写第n行数据

    for (int row = 0; row < ui->tabTotalHours->model()->rowCount(); row++)
    {
        for (int col = 0; col < ui->tabTotalHours->model()->columnCount(); col++)
        {
            QModelIndex index = ui->tabTotalHours->model()->index(row, col);
            xlsx.write(row + 2, col + 1, ui->tabTotalHours->model()->data(index).toString());
        }
    }
    // 最后，保存文件
    xlsx.saveAs(filePathName);
    QMessageBox::information(this, "提示","导出成功！");
}

void HaloKpy::on_actionAttendance_triggered()
{
    QString file_name = QFileDialog::getOpenFileName(NULL, "Open File","","Microsoft Excel(*.xlsx)");
    qDebug() <<  __FILE__ << __LINE__ << __FUNCTION__ << file_name;
    if(file_name.isEmpty())
        return;
    if(!file_name.contains(".xlsx"))
    {
        QMessageBox::warning(this, tr("提示"), tr("文件后缀错误!"));
        return;
    }
    //开始进行数据读取
    QXlsx::Document xlsx(file_name);
    QXlsx::Workbook *workBook = xlsx.workbook();
    QXlsx::Worksheet *workSheet = static_cast<QXlsx::Worksheet*>(workBook->sheet(0));//第一个标签页
    int rows=workSheet->dimension().rowCount();
    int cols = workSheet->dimension().columnCount();
    qDebug() << "row:" << rows << "col:" << cols;



//    int col = 0;
//    QString value,recDate,usrName;
//    float hours;
//    for (int i = 0; i < rows; i++) {
//        hours=0;
//        for (int j = 0; j < cols; j++) {
//            QXlsx::Cell *cell = workSheet->cellAt(i, j);
//            if (cell == NULL)
//                    continue;
//            if (cell->cellType() == 7)
//                    continue;
//            if (cell->isDateTime()) //日期
//            {
//                value = cell->dateTime().toString();
//            }
//            else
//            {
//                value = cell->value().toString();
//                if(i==1&&j==1)
//                {
//                    recDate = value.right(10);
//                }
//            }
//            if(j==1)
//            {
//                usrName=value;
//            }
//            else if(j==9||j==10||j==11||j==12||j==13||j==14||j==17)//day
//            {
//                hours+=value.toFloat()*7.5;
//            }
//            else
//            {
//                hours+=value.toFloat();
//            }

//        }
//        if(hours>0)
//            qDebug() << i << "日期"<<recDate<<"姓名" << usrName << "hours" << hours;
//    }
    QMessageBox::information(this, tr("提示"), tr("导入成功！"));
}

void HaloKpy::on_action_checkUpdate_triggered()
{
    QString strExePath = QCoreApplication::applicationDirPath();//获取应用程序可执行文件所在的目录
    QString strExeFile = strExePath +"/"+"autoupdate.exe";
    qDebug()<<"启动更新程序:"<<strExeFile;
    QStringList args;
    args<<m_versionNum<<m_exeFileName<<m_strRemoteUrl;
    QProcess::startDetached(strExeFile,args);
}

